﻿using System;
using Dsl.Ped.Designer.ViewModels;

namespace Dsl.Ped.Designer.Views
{
    /// <summary>
    /// Interaction logic for DslPedDesignerControl.xaml
    /// </summary>
    public partial class DslPedDesignerControl 
    {
        #region Fields

        /// <summary>
        /// View model of the <see cref="DslPedDesignerControl"/>
        /// </summary>
        private IDslPedDesignerControlViewModel viewModel;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="DslPedDesignerControl"/> class.
        /// </summary>
        /// <param name="viewModel">View model of the <see cref="DslPedDesignerControl"/></param>
        public DslPedDesignerControl(IDslPedDesignerControlViewModel viewModel)
        {
            this.InitializeComponent();

            // Set the view
            this.ViewModel = viewModel;

            // Wait till the initialization is done to handle events
            this.ViewModel.ViewModelChanged += this.ViewModelChanged;
        }

        #endregion

        #region Members

        /// <summary>
        /// Gets or sets the view model of the <see cref="DslPedDesignerControl"/>
        /// </summary>
        public IDslPedDesignerControlViewModel ViewModel
        {
            get
            {
                return this.viewModel;
            }
            set
            {
                this.viewModel = value;
                this.DataContext = this.viewModel;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// If the control has a focus, we should DoIdle(), otherwise
        /// we should skip till the focus is regained
        /// </summary>
        internal void DoIdle()
        {
            var vm = this.DataContext as IDslPedDesignerControlViewModel;
            if (vm != null && this.IsKeyboardFocusWithin)
            {
                vm.DoIdle();
            }
        }

        /// <summary>
        /// Handler method of the view model changes.
        /// We need to reset DataContext
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Event arguments</param>
        private void ViewModelChanged(object sender, EventArgs e)
        {
            // We have to reset DataContext when the model is updated 
            var vm = this.DataContext as IDslPedDesignerControlViewModel;
            
            // first, set to null to force regingin
            this.DataContext = null; 
            this.DataContext = vm;
        }

        #endregion
    }
}
